import os
import win32com.client
from win32com.client import constants
import time

def convert_doc_to_docx_and_pdf(doc_path, output_dir):
    word = None
    doc = None

    try:
        # Create output directory if it doesn't exist
        os.makedirs(output_dir, exist_ok=True)

        # Initialize Word application with more robust settings
        word = win32com.client.DispatchEx("Word.Application")  # Use DispatchEx for separate process
        word.Visible = False
        word.DisplayAlerts = False  # Disable alerts to prevent popups

        # Add delay to ensure Word is fully initialized
        time.sleep(2)

        # Open the document with more error handling
        doc = word.Documents.Open(
            FileName=doc_path,
            ConfirmConversions=False,
            ReadOnly=True,
            AddToRecentFiles=False
        )

        # Get the base filename without extension
        base_name = os.path.splitext(os.path.basename(doc_path))[0]

        # Save as DOCX
        docx_path = os.path.join(output_dir, f"{base_name}.docx")
        doc.SaveAs(docx_path, FileFormat=constants.wdFormatXMLDocument)
        print(f"转换成功: {doc_path} -> {docx_path}")

        # Save as PDF
        pdf_path = os.path.join(output_dir, f"{base_name}.pdf")
        doc.SaveAs(pdf_path, FileFormat=constants.wdFormatPDF)

        return True

    except Exception as e:
        print(f"转换失败 {doc_path}: {str(e)}")
        return False

    finally:
        # Proper cleanup in reverse order
        try:
            if doc is not None:
                doc.Close(SaveChanges=False)
        except Exception as e:
            print(f"关闭文档时出错: {e}")

        try:
            if word is not None:
                word.Quit()
        except Exception as e:
            print(f"关闭Word时出错: {e}")

        # Force cleanup of COM objects
        if 'doc' in locals():
            del doc
        if 'word' in locals():
            del word
        time.sleep(1)  # Allow time for cleanup

def process_folder(folder_path, output_base_dir):
    for root, dirs, files in os.walk(folder_path):
        # Create corresponding output directory
        relative_path = os.path.relpath(root, folder_path)
        output_dir = os.path.join(output_base_dir, relative_path)
        os.makedirs(output_dir, exist_ok=True)

        for file in files:
            if file.lower().endswith('.doc'):
                doc_path = os.path.join(root, file)

                print(f"正在处理: {doc_path}")

                # Convert file
                if convert_doc_to_docx_and_pdf(doc_path, output_dir):
                    try:
                        os.remove(doc_path)
                        print(f"已删除原始文件: {doc_path}")
                    except Exception as e:
                        print(f"删除文件失败 {doc_path}: {e}")
                else:
                    print(f"跳过文件由于转换失败: {doc_path}")

if __name__ == "__main__":
    input_dir = r"C:\fileDir"
    output_dir = r"C:\fileDir"

    # Check if paths exist
    if not os.path.exists(input_dir):
        print(f"输入目录不存在: {input_dir}")
    else:
        print(f"开始处理目录: {input_dir}")
        process_folder(input_dir, output_dir)
        print("处理完成")
